package com.xo.common.exception;

import com.xo.common.Result.ResultResponse;
import com.xo.common.enums.ResultEnum;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
@Hidden
@Schema(description = "全局异常处理器")
public class GlobalExceptionHandle {

    @ExceptionHandler(Exception.class)
    @Operation(summary = "全局处理异常", description = "全局处理系统中未捕获的异常，返回统一的错误响应")
    public ResultResponse<Object> handleException(Exception exception) {
        log.info("============================handleException============================", exception);
        return ResultResponse.fail(ResultEnum.SYSTEM_EXCEPTION.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public String handleValidationException(MethodArgumentNotValidException e) {
        // 获取第一个校验失败的消息
        log.info("============================MethodArgumentNotValidException============================", e);
        return  e.getBindingResult().getFieldError().getDefaultMessage();
    }

}
